<?php
/**
 * Webservice.php
 * @author StormGeoff
 * Date & Time Created: 02/16/2015 - 3:16PM
 *
 */
class Webservice {
	/**
	 * Calls response via API depending on the requested method
	 * Note: This is used on postRequestApi(), $data = array("param" => "value") ==> index.php?param=value
	 * @author GeoffreyEmbuscado 02.11.2015
	 * @param $method, $url, $data
	 * @return String
	 */
	public static function callApi( $method, $url, $data = false ) {
	
		// Method: POST, PUT, GET etc
		// Data: array('param' => 'value') -> index.php?param=value
		$curl = curl_init();
	
		switch ($method)
		{
			case 'POST':
				curl_setopt($curl, CURLOPT_POST, 1);
	
				if ( $data ) curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
				break;
			case 'PUT':
				curl_setopt($curl, CURLOPT_PUT, 1);
				break;
			default:
				if ( $data ) $url = sprintf('%s?%s', $url, http_build_query($data));
		}
	
		// Optional Authentication:
		curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		curl_setopt($curl, CURLOPT_USERPWD, "username:password");
	
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	
		$result = curl_exec($curl);
	
		curl_close($curl);
	
		return $result;
	}
	

	/**
	 * Simplified API for callApi using POST Method
	 * This function uses callApi()
	 * This function is still under going
	 * @author GeoffreyEmbuscado 02.11.2015
	 * @return String
	 */
	public static function postRequestApi() {
		
	}
	
	/**
	 * Simplified API for callApi using GET Method
	 * This function uses callApi()
	 * @author GeoffreyEmbuscado 02.11.2015
	 * @param $route, $dynamic_route
	 * @return String
	 */
	public static function getRequestApi( $route = '', $dynamic_route = array() ) {
		$route = $route;
		// Usage for GET: Webservice::getRequestApi('update_topup_client', array("qbe", 8228, 31, 0))
		
		if( count($dynamic_route) > 0 ){
			$route .= "/" . implode('/', $dynamic_route);
		}
		
		$data = json_decode(self::callApi('GET', Config::get('app.api') . $route));
		
		return $data;
	}
}